//
//  YSBusinessCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/12.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  商户页面

#import "YSBusinessCtrl.h"
#import "YSProductListGridItemCell.h"
#import "YSCategoryDataTool.h"
#import "YSProductDetailCtrl.h"
#import "YSBusinessHeaderView.h"
#import "CartView.h"


@interface YSBusinessCtrl ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property(nonatomic,weak)UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray *itemArray;
@property (assign, nonatomic) NSInteger pageIndex;
@property (assign, nonatomic) NSInteger supplierId;
@property (strong, nonatomic) YSBusinessRes *result;
@property (strong, nonatomic) CartView *cartView;
@property (strong, nonatomic) UIButton *backTopBtn;
@end

static NSString * const reuseIdentifier = @"YSProductListItemCell";
static NSString *const headerReuseIdentifier = @"YSBusinessHeaderView";

@implementation YSBusinessCtrl

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray =  [NSMutableArray array];
    }
    return _itemArray;
}

-(instancetype)initWithSupplierId:(NSInteger)supplierId{
    self = [super init];
    if(self){
        self.supplierId = supplierId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCollectionView];
    [self.collectionView.header beginRefreshing];
    
    CartView *cartView = [[CartView alloc]initWithImage:@"btn_cart"];
    [cartView addTarget:self action:@selector(tapTitleRightItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:cartView];
    _cartView = cartView;
    
    _backTopBtn = [[UIButton alloc]init];
    _backTopBtn.frame = CGRectMake(SCREENW-50, SCREENH-150, 40, 40);
    [_backTopBtn setBackgroundImage:[UIImage imageNamed:@"icon_back_top"] forState:UIControlStateNormal];
    [_backTopBtn addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];
    [_backTopBtn setHidden:YES];
    [self.view insertSubview:_backTopBtn aboveSubview:self.view];
}

-(void)toTop:(UIButton *)toTopBtn{
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView.contentOffset.y>scrollView.height){
        [_backTopBtn setHidden:NO];
    }else{
        [_backTopBtn setHidden:YES];
    }
}

-(void)tapTitleRightItem:(UIBarButtonItem *)btnItem{
    [Utils showCartCtrl:self];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(_cartView){
        NSInteger num =  [DefaultsHelper integerForKey:kCartIndex];
        [_cartView setNum:num];
    }
}

-(void)initCollectionView{
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    [flowLayout setMinimumLineSpacing:5];
    [flowLayout setMinimumInteritemSpacing:5];
    
    UICollectionView *collectionView  =[[UICollectionView alloc]initWithFrame:    CGRectMake(0, 0, SCREENW, SCREENH) collectionViewLayout:flowLayout];
    collectionView.height = collectionView.height-NavWithStatusBarH;
    [collectionView setBackgroundColor:PUBLIC_BG];
    [collectionView registerClass:[YSProductListGridItemCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    //注册头部View
    [collectionView  registerClass:[YSBusinessHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerReuseIdentifier];
    
    [collectionView setDelegate:self];
    [collectionView setDataSource:self];
    [collectionView setAlwaysBounceVertical:YES];
    [collectionView registerNib:[UINib nibWithNibName:reuseIdentifier bundle: [NSBundle mainBundle]] forCellWithReuseIdentifier:reuseIdentifier];
    [self.view addSubview:collectionView];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    collectionView.header = header;
    collectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    
    self.collectionView = collectionView;
}

-(void)headerRefresh{
    self.pageIndex = 0;
    [self requestData];
}

-(void)footerRefresh{
    self.pageIndex ++;
    [self requestData];
}

-(void)recomleteRefresh{
    [self.collectionView.header endRefreshing];
    [self.collectionView.footer endRefreshing];
}

-(void)requestData{
    [YSCategoryDataTool getBusinessWithSupplierId:self.supplierId pageIndex:self.pageIndex success:^(YSBusinessRes *result) {
        [self recomleteRefresh];
        if(result.isSucc){
            _result = result;
            if(self.pageIndex == 0){
                [self.navigationItem setTitle:result.supplier.supplierName];
                [self.itemArray removeAllObjects];
            }
            [self.itemArray addObjectsFromArray:result.productList];
            [self.collectionView reloadData];
        }else{
           ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
         [self recomleteRefresh];
         ShowTips(kRequestFailure);
    }];
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YSProductListGridItemCell *cell = [YSProductListGridItemCell cellWithCollectionView:collectionView indexPath:indexPath];
    [cell setProd:self.itemArray[indexPath.row]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREENW-25)/2, 250);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger prodId = [self.itemArray[indexPath.row] prodId];
    YSProductDetailCtrl *ctrl =  [[YSProductDetailCtrl alloc]initWithProdId:prodId];
    [self.navigationController pushViewController:ctrl animated:YES];
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10,10,10,10);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath = %@",indexPath);
    YSBusinessHeaderView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerReuseIdentifier forIndexPath:indexPath];
    [headView setSupplier:_result.supplier];
    [headView setBackgroundColor:PUBLIC_CARD_BG];
    return headView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    CGSize size = [_result.supplier.supplierDesc sizeWithFont:SYS_FONT(15) constrainedToSize:CGSizeMake(SCREENW-YSPublicXInset*2, MAXFLOAT)];

    return CGSizeMake(SCREENW, HeaderImgHeight+size.height+YSPublicXInset*2);
}

@end
